<template>
  <div class="mine-information-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="浏览个人信息"
      left-arrow
      @click-left="goBack"
      :style="{ backgroundColor: '#FFD847' }"
    />

    <!-- 头像 -->
    <van-cell class="avatar-cell" title="头像">
      <template #value>
        <van-image
          class="avatar-image"
          :src="userInfo.avatar || '/default-avatar.png'"
          round
          fit="cover"
        />
      </template>
    </van-cell>

    <!-- ID -->
    <van-cell title="ID">
      <template #value>
        <span class="info-text">{{ userInfo.id }}</span>
      </template>
    </van-cell>

    <!-- 用户名 -->
    <van-cell title="用户名">
      <template #value>
        <span class="info-text">{{ userInfo.username || '未填写' }}</span>
      </template>
    </van-cell>

    <!-- 昵称 -->
    <van-cell title="昵称">
      <template #value>
        <span class="info-text">{{ userInfo.nickname || '笑谈' }}</span>
      </template>
    </van-cell>

    <!-- 性别 -->
    <van-cell title="性别">
      <template #value>
        <span class="info-text">{{ userInfo.gender || '未填写' }}</span>
      </template>
    </van-cell>

    <!-- 手机号 -->
    <van-cell title="手机号">
      <template #value>
        <span class="info-text">{{ userInfo.mobile || '未绑定' }}</span>
      </template>
    </van-cell>

    <!-- 邮箱 -->
    <van-cell title="邮箱">
      <template #value>
        <span class="info-text">{{ userInfo.email || '未填写' }}</span>
      </template>
    </van-cell>

    <!-- 导出按钮 -->
    <div class="export-section">
      <van-button 
        type="primary" 
        block 
        round
        icon="down"
        @click="handleExport"
        :loading="exporting"
      >
        导出个人信息
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUser } from '@/api'
import { showToast } from 'vant'
import { getToken } from '@/utils/token'
import { useRouter } from 'vue-router'

const router = useRouter()
const exporting = ref(false)

// 用户信息
const userInfo = ref({
  id: '',
  username: '',
  nickname: '',
  email: '',
  gender: '',
  mobile: '',
  avatar: '',
})

// 获取用户信息
const fetchUserInfo = async () => {
  const token = getToken()
  if (!token) {
    showToast('请先登录')
    router.push({ name: 'login' })
    return
  }

  try {
    const data = await getUser()
    console.log('用户信息:', data)
    
    if (data.User) {
      userInfo.value = {
        id: data.User.id || '',
        username: data.User.username || '',
        nickname: data.User.nickname || '',
        email: data.User.email || '',
        gender: data.User.gender || '',
        mobile: data.User.mobile || '',
        avatar: data.User.avatar || '',
        openid: data.User.openid || '',
        emergencyMobile: data.User.emergencyMobile || ''
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    showToast('获取信息失败')
  }
}

// 导出个人信息为txt文件
const handleExport = () => {
  try {
    exporting.value = true

    // 构建导出内容
    const exportContent = `
═══════════════════════════════════
        鲨鱼记账 - 个人信息
═══════════════════════════════════

【基本信息】
用户ID：${userInfo.value.id || '无'}
用户名：${userInfo.value.username || '未设置'}
昵称：${userInfo.value.nickname || '未设置'}
性别：${userInfo.value.gender || '未填写'}

【联系方式】
手机号：${userInfo.value.mobile || '未绑定'}
邮箱：${userInfo.value.email || '未填写'}

【其他信息】
头像：${userInfo.value.avatar || '未设置'}

═══════════════════════════════════
导出时间：${new Date().toLocaleString('zh-CN')}
═══════════════════════════════════
    `.trim()

    // 创建Blob对象
    const blob = new Blob([exportContent], { type: 'text/plain;charset=utf-8' })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 设置文件名
    const fileName = `鲨鱼记账_个人信息_${userInfo.value.username || userInfo.value.id}_${Date.now()}.txt`
    link.download = fileName
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    
    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    showToast('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    showToast('导出失败，请重试')
  } finally {
    exporting.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style lang='scss' scoped>
.mine-information-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;

  :deep(.van-nav-bar) {
    .van-nav-bar__title {
      color: #333;
      font-weight: bold;
    }
    
    // 返回箭头样式
    .van-nav-bar__arrow {
      color: #333;           /* 箭头颜色 */
      font-size: 18px;       /* 箭头大小 */
      font-weight: 600;      /* 箭头粗细 */
    }
  }

  :deep(.avatar-cell) {
    min-height: 80px;
    padding: 10px 16px;
    
    .van-cell__title {
      display: flex;
      align-items: center;
    }
    
    .van-cell__value {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .avatar-image {
    position: absolute;
    right: 0;
    width: 60px;
    height: 60px;
    flex-shrink: 0;
  }

  .info-text {
    color: #666;
  }

  // 导出按钮区域
  .export-section {
    margin: 30px 15px;
    
    :deep(.van-button) {
      height: 50px;
      background: linear-gradient(to right, #FFD847, #FFC107);
      border: none;
      color: #333;
      font-size: 16px;
      font-weight: 500;
      box-shadow: 0 2px 8px rgba(255, 215, 71, 0.4);
      
      &:active {
        opacity: 0.8;
      }
      
      .van-icon {
        font-size: 18px;
      }
    }
  }

  // 分隔线样式
  :deep(.van-cell) {
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
  }
}
</style>